﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Web;
using JJY.CommonHelper;
using NBA.DataAccess;
using NBA.Entity;

namespace NBA.Business
{
    public class MatchListMonitor4Sina
    {
        private const string DOMAINNAME = "http://nba.sports.sina.com.cn/";
        private static DaTeamInfo daTeamInfo = new DaTeamInfo();
        private static DaMatchInfo daMatchInfo = new DaMatchInfo();
        private static DaMatchTeamData daMatchTeamData = new DaMatchTeamData();

        public static int ReadMatchList(string urlMatchList)
        {
            int result = 0;
            string strMatchList =
                HttpUtility.HtmlDecode(HttpRequestService.GetHtmlSourceByUrl(urlMatchList, Encoding.Default)
                .HtmlToString().Trim());
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(strMatchList);

            string matchYear = doc.DocumentNode.SelectNodes(@"//strong")[0].InnerText.Substring(0, 4);
            string matchDate = string.Empty;

            HtmlNodeCollection nodeMatchList =
                doc.DocumentNode.SelectNodes(@"//div[@id='table980middle']/div/table/tr");

            Dictionary<string, int> dicUrl = new Dictionary<string, int>();

            if (nodeMatchList != null)
            {
                foreach (HtmlNode htmlNode in nodeMatchList)
                {
                    HtmlNodeCollection htmlNodeTdSet = doc.DocumentNode.SelectNodes(htmlNode.XPath + "/td");

                    if (htmlNodeTdSet.Count == 12)
                    {
                        if (htmlNodeTdSet[0].InnerText.IndexOf("星期") > -1)
                        {
                            matchDate = matchYear + "-" +
                                htmlNodeTdSet[0].InnerText.Substring(0, 6).Replace("月", "-").Replace("日", string.Empty);
                            if (int.Parse(htmlNodeTdSet[0].InnerText.Substring(0, 2)) < 9)
                            {
                                matchDate = (int.Parse(matchYear) + 1).ToString() + "-" +
                                    htmlNodeTdSet[0].InnerText.Substring(0, 6).Replace("月", "-").Replace("日", string.Empty);
                            }
                        }
                        else
                        {
                            string matchDateTime = matchDate + " " + htmlNodeTdSet[0].InnerText.Substring(0, 5) + ":00";
                            string url = doc.DocumentNode.SelectNodes(htmlNodeTdSet[8].XPath + "/a")[0].Attributes["href"].Value;
                            if (!dicUrl.ContainsKey(url))
                            {                                
                                ReadMatch(DOMAINNAME + url, DateTime.Parse(matchDateTime));
                                dicUrl.Add(url, 1);
                            }
                        }
                    }
                }
            }
            return result;
        }

        private static bool ReadMatch(string urlMatch, DateTime matchDateTime)
        {
            bool result = false;

            string strMatchInfo = HttpUtility.HtmlDecode(HttpRequestService.GetHtmlSourceByUrl(urlMatch,
                Encoding.Default).HtmlToString().Trim());

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(strMatchInfo);

            Guid visitingTeamId = Guid.Empty;
            Guid homeTeamId = Guid.Empty;
            Guid matchId = Guid.Empty;

            ReadTeamDataBasic(doc, matchDateTime, out matchId, out visitingTeamId, out homeTeamId);
            ReadTeamDataDetails(doc, matchId, visitingTeamId, homeTeamId);


            result = true;
            return result;
        }

        private static bool ReadTeamDataBasic(HtmlDocument doc, DateTime matchDateTime, out Guid matchId,
            out Guid visitingTeamId, out Guid homeTeamId)
        {
            bool result = false;

            HtmlNodeCollection nodeTeamNameSet = doc.DocumentNode.SelectNodes("//a[@class='tlogo']");
            HtmlNodeCollection nodeTeamScore = doc.DocumentNode.SelectNodes("//td[@class='num']");

            visitingTeamId = daTeamInfo.InsertOrUpdate(new TeamInfo()
            {
                TeamId = Guid.NewGuid(),
                TeamName = nodeTeamNameSet[0].InnerText.Trim()
            });

            homeTeamId = daTeamInfo.InsertOrUpdate(new TeamInfo()
            {
                TeamId = Guid.NewGuid(),
                TeamName = nodeTeamNameSet[1].InnerText.Trim()
            });

            HtmlNode nodeScoreTable = doc.DocumentNode.SelectSingleNode("//table[@class='score']");
            HtmlNodeCollection nodeVisitingScore = doc.DocumentNode.SelectNodes(nodeScoreTable.XPath + "/tr[2]/td");
            HtmlNodeCollection nodeHomeScore = doc.DocumentNode.SelectNodes(nodeScoreTable.XPath + "/tr[3]/td");

            short visitingOt = 0;
            short homeOt = 0;

            if (nodeVisitingScore.Count > 4)
            {
                for (int i = 4; i < nodeVisitingScore.Count - 1; i++)
                {
                    visitingOt += short.Parse(nodeVisitingScore[i].InnerText);
                    homeOt += short.Parse(nodeHomeScore[i].InnerText);
                }
            }

            MatchInfo matchInfo = new MatchInfo()
            {
                MatchId = Guid.NewGuid(),
                MatchDateTime = matchDateTime,
                VisitingTeamId = visitingTeamId,
                HomeTeamId = homeTeamId,
                SeasonYear = 2011,
                VisitingFirst = short.Parse(nodeVisitingScore[0].InnerText),
                VisitingSecond = short.Parse(nodeVisitingScore[1].InnerText),
                VisitingThird = short.Parse(nodeVisitingScore[2].InnerText),
                VisitingFourth = short.Parse(nodeVisitingScore[3].InnerText),
                VisitingScore = short.Parse(nodeTeamScore[0].InnerText),
                VisitingOt = visitingOt,
                HomeFirst = short.Parse(nodeHomeScore[0].InnerText),
                HomeSecond = short.Parse(nodeHomeScore[1].InnerText),
                HomeThird = short.Parse(nodeHomeScore[2].InnerText),
                HomeFourth = short.Parse(nodeHomeScore[3].InnerText),
                HomeScore = short.Parse(nodeTeamScore[1].InnerText),
                HomeOt = homeOt,
                OtCount = (byte)(nodeVisitingScore.Count - 4)
            };
            matchId = daMatchInfo.InsertOrUpdate(matchInfo);

            result = true;
            return result;
        }

        private static bool ReadTeamAndMemberDataDetails(HtmlDocument doc, Guid matchId, Guid visitingTeamId,
            Guid homeTeamId)
        {
            bool result = false;

            #region html repair
            string docTemp = doc.DocumentNode.SelectSingleNode("//div[@id='main']/div")
                .InnerHtml.HtmlToString().Replace("</td><tr", "</td></tr><tr");
            while (docTemp.IndexOf("</tr></tr>") > -1)
            {
                docTemp = docTemp.Replace("</tr></tr>", "</tr>");
            }
            doc.LoadHtml(docTemp);
            #endregion

            //HtmlNodeCollection nodeTableDetails = doc.DocumentNode.SelectNodes("//table");

            MatchTeamData visitingMatchTeamData = new MatchTeamData();
            MatchTeamData homeMatchTeamData = new MatchTeamData();


            HtmlNodeCollection nodeVisitingDetails =
                doc.DocumentNode.SelectNodes("table[2]/tr[2]/td/table/tr");
            HtmlNodeCollection nodeHomeDetails =
                doc.DocumentNode.SelectNodes("table[3]/tr[2]/td/table/tr");

            visitingMatchTeamData.MatchId = matchId;
            visitingMatchTeamData.TeamId = visitingTeamId;
            homeMatchTeamData.MatchId = matchId;
            homeMatchTeamData.TeamId = homeTeamId;
            if (int.Parse(nodeVisitingDetails[1].InnerText.Trim()) > 0 && nodeVisitingDetails.Count > 0)
            {
                short visitingTotalShot =
                    short.Parse(nodeVisitingDetails[2].InnerText.Split('-')[1].Trim());
                short visitingTotalGoal =
                    short.Parse(nodeVisitingDetails[2].InnerText.Split('-')[0].Trim());
                short visitingShot3 =
                    short.Parse(nodeVisitingDetails[3].InnerText.Split('-')[1].Trim());
                short visitingShot3Goal =
                    short.Parse(nodeVisitingDetails[3].InnerText.Split('-')[0].Trim());
                short visitingFreeThrow =
                    short.Parse(nodeVisitingDetails[4].InnerText.Split('-')[1].Trim());
                short visitingFreeThrowGoal =
                    short.Parse(nodeVisitingDetails[4].InnerText.Split('-')[0].Trim());
                visitingMatchTeamData.Shot3 = visitingShot3;
                visitingMatchTeamData.Goal3 = visitingShot3Goal;
                visitingMatchTeamData.Shot2 = (short)(visitingTotalShot - visitingShot3);
                visitingMatchTeamData.Goal2 = (short)(visitingTotalGoal - visitingShot3Goal);
                visitingMatchTeamData.FreeThrow = visitingFreeThrow;
                visitingMatchTeamData.FreeThrowGoal = visitingFreeThrowGoal;
                visitingMatchTeamData.OffensiveRebound = short.Parse(nodeVisitingDetails[5].InnerText.Trim());
                visitingMatchTeamData.DefensiveRebound = short.Parse(nodeVisitingDetails[6].InnerText.Trim());
                visitingMatchTeamData.Assist = short.Parse(nodeVisitingDetails[8].InnerText.Trim());
                visitingMatchTeamData.Steal = short.Parse(nodeVisitingDetails[9].InnerText.Trim());
                visitingMatchTeamData.Block = short.Parse(nodeVisitingDetails[10].InnerText.Trim());
                visitingMatchTeamData.Turnover = short.Parse(nodeVisitingDetails[11].InnerText.Trim());
                visitingMatchTeamData.Foul = short.Parse(nodeVisitingDetails[12].InnerText.Trim());
                visitingMatchTeamData.Scoring = short.Parse(nodeVisitingDetails[13].InnerText.Trim());

                short homeTotalShot =
                    short.Parse(nodeHomeDetails[2].InnerText.Split('-')[1].Trim());
                short homeTotalGoal =
                    short.Parse(nodeHomeDetails[2].InnerText.Split('-')[0].Trim());
                short homeShot3 =
                    short.Parse(nodeHomeDetails[3].InnerText.Split('-')[1].Trim());
                short homeShot3Goal =
                    short.Parse(nodeHomeDetails[3].InnerText.Split('-')[0].Trim());
                short homeFreeThrow =
                    short.Parse(nodeHomeDetails[4].InnerText.Split('-')[1].Trim());
                short homeFreeThrowGoal =
                    short.Parse(nodeHomeDetails[4].InnerText.Split('-')[0].Trim());
                homeMatchTeamData.Shot3 = homeShot3;
                homeMatchTeamData.Goal3 = homeShot3Goal;
                homeMatchTeamData.Shot2 = (short)(homeTotalShot - homeShot3);
                homeMatchTeamData.Goal2 = (short)(homeTotalGoal - homeShot3Goal);
                homeMatchTeamData.FreeThrow = homeFreeThrow;
                homeMatchTeamData.FreeThrowGoal = homeFreeThrowGoal;
                homeMatchTeamData.OffensiveRebound = short.Parse(nodeHomeDetails[5].InnerText.Trim());
                homeMatchTeamData.DefensiveRebound = short.Parse(nodeHomeDetails[6].InnerText.Trim());
                homeMatchTeamData.Assist = short.Parse(nodeHomeDetails[8].InnerText.Trim());
                homeMatchTeamData.Steal = short.Parse(nodeHomeDetails[9].InnerText.Trim());
                homeMatchTeamData.Block = short.Parse(nodeHomeDetails[10].InnerText.Trim());
                homeMatchTeamData.Turnover = short.Parse(nodeHomeDetails[11].InnerText.Trim());
                homeMatchTeamData.Foul = short.Parse(nodeHomeDetails[12].InnerText.Trim());
                homeMatchTeamData.Scoring = short.Parse(nodeHomeDetails[13].InnerText.Trim());
            }

            if (daMatchTeamData.InsertOrUpdate(visitingMatchTeamData) > 0
                && daMatchTeamData.InsertOrUpdate(homeMatchTeamData) > 0)
            {
                result = true;
            }

            return result;
        }

        private static bool ReadMemberDetails(HtmlNodeCollection htmlNodeTrSet, int isVisiting)
        {
            bool result = false;

            foreach (HtmlNode htmlNodeTr in htmlNodeTrSet)
            {
                HtmlNodeCollection htmlNodeTdSet = htmlNodeTr.SelectNodes("/td");
                int isRotation = 0;
                if (htmlNodeTdSet.Count == 14)
                {
                    if (htmlNodeTdSet[0].InnerText.Trim() == "首发球员")
                    {
                        isRotation = 1;
                    }
                    else if (htmlNodeTdSet[0].InnerText.Trim() == "替补球员")
                    {
                        isRotation = 0;
                    }
                    else if (htmlNodeTdSet[0].InnerText.Trim() == "总计")
                    {

                    }
                    else
                    {
                        
                    }
                }
                else if (htmlNodeTdSet.Count == 2)
                {

                }
            }
            return result;
        }

        [Obsolete]
        private static bool ReadTeamDataDetails(HtmlDocument doc, Guid matchId, Guid visitingTeamId,
            Guid homeTeamId)
        {
            bool result = false;

            #region html repair
            string docTemp = doc.DocumentNode.SelectSingleNode("//div[@id='main']/div")
                .InnerHtml.HtmlToString().Replace("</td><tr", "</td></tr><tr");
            while (docTemp.IndexOf("</tr></tr>") > -1)
            {
                docTemp = docTemp.Replace("</tr></tr>", "</tr>");
            }
            doc.LoadHtml(docTemp);
            #endregion

            //HtmlNodeCollection nodeTableDetails = doc.DocumentNode.SelectNodes("//table");

            MatchTeamData visitingMatchTeamData = new MatchTeamData();
            MatchTeamData homeMatchTeamData = new MatchTeamData();


            HtmlNodeCollection nodeVisitingDetails =
                doc.DocumentNode.SelectNodes("table[2]/tr[2]/td/table/tr[last()]/td");
            HtmlNodeCollection nodeHomeDetails =
                doc.DocumentNode.SelectNodes("table[3]/tr[2]/td/table/tr[last()]/td");

            visitingMatchTeamData.MatchId = matchId;
            visitingMatchTeamData.TeamId = visitingTeamId;
            homeMatchTeamData.MatchId = matchId;
            homeMatchTeamData.TeamId = homeTeamId;
            if (int.Parse(nodeVisitingDetails[1].InnerText.Trim())>0 && nodeVisitingDetails.Count > 0)
            {
                short visitingTotalShot =
                    short.Parse(nodeVisitingDetails[2].InnerText.Split('-')[1].Trim());
                short visitingTotalGoal =
                    short.Parse(nodeVisitingDetails[2].InnerText.Split('-')[0].Trim());
                short visitingShot3 =
                    short.Parse(nodeVisitingDetails[3].InnerText.Split('-')[1].Trim());
                short visitingShot3Goal =
                    short.Parse(nodeVisitingDetails[3].InnerText.Split('-')[0].Trim());
                short visitingFreeThrow =
                    short.Parse(nodeVisitingDetails[4].InnerText.Split('-')[1].Trim());
                short visitingFreeThrowGoal =
                    short.Parse(nodeVisitingDetails[4].InnerText.Split('-')[0].Trim());                
                visitingMatchTeamData.Shot3 = visitingShot3;
                visitingMatchTeamData.Goal3 = visitingShot3Goal;
                visitingMatchTeamData.Shot2 = (short)(visitingTotalShot - visitingShot3);
                visitingMatchTeamData.Goal2 = (short)(visitingTotalGoal - visitingShot3Goal);
                visitingMatchTeamData.FreeThrow = visitingFreeThrow;
                visitingMatchTeamData.FreeThrowGoal = visitingFreeThrowGoal;
                visitingMatchTeamData.OffensiveRebound = short.Parse(nodeVisitingDetails[5].InnerText.Trim());
                visitingMatchTeamData.DefensiveRebound = short.Parse(nodeVisitingDetails[6].InnerText.Trim());
                visitingMatchTeamData.Assist = short.Parse(nodeVisitingDetails[8].InnerText.Trim());
                visitingMatchTeamData.Steal = short.Parse(nodeVisitingDetails[9].InnerText.Trim());
                visitingMatchTeamData.Block = short.Parse(nodeVisitingDetails[10].InnerText.Trim());
                visitingMatchTeamData.Turnover = short.Parse(nodeVisitingDetails[11].InnerText.Trim());
                visitingMatchTeamData.Foul = short.Parse(nodeVisitingDetails[12].InnerText.Trim());
                visitingMatchTeamData.Scoring = short.Parse(nodeVisitingDetails[13].InnerText.Trim());

                short homeTotalShot =
                    short.Parse(nodeHomeDetails[2].InnerText.Split('-')[1].Trim());
                short homeTotalGoal =
                    short.Parse(nodeHomeDetails[2].InnerText.Split('-')[0].Trim());
                short homeShot3 =
                    short.Parse(nodeHomeDetails[3].InnerText.Split('-')[1].Trim());
                short homeShot3Goal =
                    short.Parse(nodeHomeDetails[3].InnerText.Split('-')[0].Trim());
                short homeFreeThrow =
                    short.Parse(nodeHomeDetails[4].InnerText.Split('-')[1].Trim());
                short homeFreeThrowGoal =
                    short.Parse(nodeHomeDetails[4].InnerText.Split('-')[0].Trim());                                
                homeMatchTeamData.Shot3 = homeShot3;
                homeMatchTeamData.Goal3 = homeShot3Goal;
                homeMatchTeamData.Shot2 = (short)(homeTotalShot - homeShot3);
                homeMatchTeamData.Goal2 = (short)(homeTotalGoal - homeShot3Goal);
                homeMatchTeamData.FreeThrow = homeFreeThrow;
                homeMatchTeamData.FreeThrowGoal = homeFreeThrowGoal;
                homeMatchTeamData.OffensiveRebound = short.Parse(nodeHomeDetails[5].InnerText.Trim());
                homeMatchTeamData.DefensiveRebound = short.Parse(nodeHomeDetails[6].InnerText.Trim());
                homeMatchTeamData.Assist = short.Parse(nodeHomeDetails[8].InnerText.Trim());
                homeMatchTeamData.Steal = short.Parse(nodeHomeDetails[9].InnerText.Trim());
                homeMatchTeamData.Block = short.Parse(nodeHomeDetails[10].InnerText.Trim());
                homeMatchTeamData.Turnover = short.Parse(nodeHomeDetails[11].InnerText.Trim());
                homeMatchTeamData.Foul = short.Parse(nodeHomeDetails[12].InnerText.Trim());
                homeMatchTeamData.Scoring = short.Parse(nodeHomeDetails[13].InnerText.Trim());
            }

            if (daMatchTeamData.InsertOrUpdate(visitingMatchTeamData) > 0
                && daMatchTeamData.InsertOrUpdate(homeMatchTeamData) > 0)
            {
                result = true;
            }

            return result;
        }
    }
}
